package com.promotores;

				
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;

import com.promotores.R;
import com.promotores.util.ImageDownloader;
import com.promotores.util.Parametros;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityAprobarEvento extends Activity implements OnClickListener {
	String strIdEvento;
	String nombEvento;
	BeanEvento evento;
	GestorEvento dbEvento;
	Button btnAprobar;
	Button btnPromocion;
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pr_aprobar_evento);
		btnAprobar = (Button)findViewById(R.id.btnAprobar);
		btnAprobar.setOnClickListener(this);
		btnPromocion = (Button)findViewById(R.id.btnPromocion);
		btnPromocion.setOnClickListener(this);
		strIdEvento = this.getIntent().getStringExtra("idEvento");
		dbEvento = new GestorEvento(this);
		evento = dbEvento.getEvento(Integer.parseInt(strIdEvento));
		nombEvento = evento.getNombre();
		Parametros.setCurrent_event(nombEvento);
		TextView t=new TextView(this); 
	    t=(TextView)findViewById(R.id.lblDatNombreEvento); 
	    t.setText(evento.getNombre());
	    t=(TextView)findViewById(R.id.txtDatFechas); 
	    if (evento.getFechaIni().compareTo(evento.getFechaFin()) != 0)
	    	t.setText(evento.getFechaIni() + " a " + evento.getFechaFin());
	    else
	    	t.setText(evento.getFechaIni());
	    GestorTipoEvento dbTipoEvento = new GestorTipoEvento(this); 
	    BeanTipoEvento tipoEvento = dbTipoEvento.getTipoEvento(evento.getTipoEvento());
	    t=(TextView)findViewById(R.id.txtDatTipoEvento); 
	    t.setText(tipoEvento.getTipoEvento());
//		try {
//			  ImageView i = (ImageView) findViewById(R.id.imgEvento);
//			  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://"+evento.getUrlImagen()).getContent());
//			  i.setImageBitmap(bitmap); 
//			} catch (MalformedURLException e) {
//			  e.printStackTrace();
//			} catch (IOException e) {
//			  e.printStackTrace();
//		}
	    ImageView im = (ImageView) findViewById(R.id.imgEvento);
	    ImageDownloader imageDownloader = new ImageDownloader();
	    imageDownloader.download("http://"+evento.getUrlImagen(), im);
		//Ambiente
		t=(TextView)findViewById(R.id.txtDatAmbiente); 
	    t.setText(evento.getAmbiente());
	    //Zonas
	    GestorZona gestorZona = new GestorZona(this);
	    evento.setZona(gestorZona.getAllZonaByEvento(Integer.parseInt(strIdEvento)));
	    if (evento.getZona()!=null){
		    t=(TextView)findViewById(R.id.txtDatZonasTarifas);
		    String zonaAux="";
		    for (int i=0; i<evento.getZona().size(); i++){
		    	zonaAux+=evento.getZona().get(i).getNombre()+" "+evento.getZona().get(i).getDescripcion()
		    			+" - Aforo:"+evento.getZona().get(i).getAforo()+", Tarifa:"+evento.getZona().get(i).getFare();
		    	if (i!=evento.getZona().size()-1) zonaAux+="\n";
		    }
		    t.setText(zonaAux);
	    }
	    ImageButton offline = (ImageButton)findViewById(R.id.imgOfflineMode);
        offline.setOnClickListener(this);
        if (Parametros.isOffline_mode()){
        	offline.setVisibility(View.VISIBLE);
        }
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if (Parametros.isOffline_mode()){
			ImageButton offline = (ImageButton)findViewById(R.id.imgOfflineMode);
			offline.setVisibility(View.VISIBLE);
			offline.invalidate();
        }
	}

	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
	        switch (which){
	        case DialogInterface.BUTTON_POSITIVE:
	        	Toast.makeText(getApplicationContext(), "Evento aprobado", Toast.LENGTH_LONG).show();
        		evento.setEstado("4");
        		dbEvento.updateEvento(evento);
//        		evento.setUpdated_at("");  
        		dbEvento.updateEvento(evento);	
        		dbEvento.updateFlag(evento,"0");
        		JsonEvento jEvento  =  new JsonEvento();
    			try {
    				int result = jEvento.postData(Integer.parseInt(strIdEvento),Integer.parseInt(evento.getEstado()));
    				if (result!=0) dbEvento.updateFlag(evento,"1");
    				if (result==0 && !isNetworkAvailable()){
    					Toast.makeText(getApplicationContext(), "Modo Offline Activado\nNo hay conexión disponible", Toast.LENGTH_LONG).show();
    					Parametros.setOffline_mode(true);
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			} catch (JSONException e) {
    				e.printStackTrace();
    				
    			}
    			evento = dbEvento.getEvento(evento.getId());
    			Log.e("prueba", evento.getSaved());
        		Intent intent = new Intent();
        		intent.setClass(getApplicationContext(), ActivityMenuPromotores.class);
        		startActivity(intent);        		
	        	finish();
	        	break;

	        case DialogInterface.BUTTON_NEGATIVE:
	            //No button clicked
	            break;
	        }
	    }
	};
	 
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.btnAprobar){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("¿Está seguro de aprobar el evento?").setPositiveButton("Yes", dialogClickListener)
		    .setNegativeButton("No", dialogClickListener).show();
		}else if (v.getId() == R.id.btnPromocion){
			Intent intent = new Intent();
			intent.putExtra("idEvento", strIdEvento);
			intent.putExtra("fechaini",evento.getFechaIni());
			intent.putExtra("fechafin",evento.getFechaFin());
			intent.putExtra("nombEvento",nombEvento);
			intent.setClass(this, ActivityListarPromociones.class);
			startActivity(intent);
		}
	}
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
}
